const express = require('express')
const bodyParser = require('body-parser')
const { expressjwt: jwt } = require('express-jwt')
const userRouterHandler = require('./routerHandler/user')
const authMiddleware = require('./middleware/auth')
const utilsMiddleware = require('./middleware/utils')
const routes = require('./routes/user')
const config = require('./config')
const cors = require('cors')
const app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// 应用中间件：记录请求日志
app.use(authMiddleware.logRequest)
// 跨域处理中间件
app.all(authMiddleware.handleCors)

// 优化 res.send()代码 - 响应数据的中间件
app.use(utilsMiddleware.responseHandler)

// cors

// const corsOptions = {
//   origin: 'http://127.0.0.1:5173'
//   //...
// }

// app.use('*', cors(corsOptions))

// 解析 Token 后，获取用户信息
app.use(authMiddleware.onParseToken)
// 用于验证Token
app.use(authMiddleware.onVerifyToken)

// 中间件记得前面加 / 否则会匹配不到路由
app.use(config.routerFix + '/users', routes)

// app.get('/hello', userRouterHandler.handleTest)

app.post(config.routerFix + '/signIn', userRouterHandler.handleSignIn)
// app.post('/signUp', userRouterHandler.handleSignUp)
console.log('routes', routes)

app.use(function (req, res, next) {
  res.status(404).send('Not found!')
})

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

app.listen(5000, function () {
  console.log('127.0.0.1:5000 running ')
})
